package com.fundamentalesandroid;

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;

public class PlayerTouch extends Activity implements OnCompletionListener, 
										OnClickListener, OnTouchListener{

	MediaPlayer mediaPlayer;
	View theView;
	Button stopButton, startButton;
	
	int position=0;

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if(event.getAction() == MotionEvent.ACTION_MOVE){
			if(mediaPlayer.isPlaying()){
				position=(int) (event.getX()*mediaPlayer.getDuration()/theView.getWidth());
				Log.v("SEEK",""+position);
				mediaPlayer.seekTo(position);
			}
		}
		return true;
	}

	@Override
	public void onClick(View v) {
		if(v == stopButton){
			mediaPlayer.pause();
			//mediaPlayer.release();
		}else{
			if(v == startButton){
				if(!mediaPlayer.isPlaying()){
					mediaPlayer.start();
				}
			}
		}
	}

	@Override
	public void onCompletion(MediaPlayer arg0) {
		mediaPlayer.start();
		mediaPlayer.seekTo(position);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.player2);
		
		stopButton=(Button) this.findViewById(R.id.StopButton);
		startButton=(Button) this.findViewById(R.id.StartButton);
		
		startButton.setOnClickListener(this);
		stopButton.setOnClickListener(this);
		
		theView=this.findViewById(R.id.theview);
		
		theView.setOnTouchListener(this);
		
		mediaPlayer=MediaPlayer.create(this,R.raw.acdc);
		mediaPlayer.setOnCompletionListener(this);
		mediaPlayer.start();
	}
	

}
